<?php

namespace app\admin\controller\qingdongwms\stock;

use addons\qingdongwms\model\ExamineRecord;
use addons\qingdongwms\model\FormField;
use addons\qingdongwms\model\InstockOther;
use addons\qingdongwms\model\InstockProduct;
use addons\qingdongwms\model\ProductPart;
use addons\qingdongwms\model\Product;
use addons\qingdongwms\model\Goods as GoodsModel;
use addons\qingdongwms\model\Ratio;
use addons\qingdongwms\model\Staff;
use addons\qingdongwms\model\Warehouse;
use app\admin\controller\qingdongwms\Base;
use addons\qingdongwms\model\Form;
use addons\qingdongwms\model\Customer;
use addons\qingdongwms\model\OperationLog;
use addons\qingdongwms\model\Record;
use addons\qingdongwms\model\Flow;
use addons\qingdongwms\model\Supplier;
use app\admin\controller\qingdongwms\product\Goods;
use addons\qingdongwms\model\Message;
use think\Db;
use think\Exception;


/**
 * 入库单
 * @icon fa fa-sign-in
 */
class Instock extends Base
{
    protected $relationSearch = true;
    /**
     * @var \addons\qingdongwms\model\Instock
     */
    protected $model = null;


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \addons\qingdongwms\model\Instock;
    }


    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            //0:全部 1：我负责的 2：下属负责的
            $type = input('type', 0);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            switch ($type) {
                case 1:
                    $staff = Staff::info();
                    $wheres['owner_staff_id'] = $staff->id;
                    break;
                case 2:
                    $wheres['owner_staff_id'] = array('in', Staff::getLowerStaffId());
                    break;
                default:
                    $wheres['owner_staff_id'] = array('in', Staff::getMyStaffIds());
                    break;

            }
            $ids = [];
            $group_id = input('group_id');
            $staff_id = input('staff_id');
            if ($group_id) {//角色组
                $ids = Staff::getGroupStaffIds($group_id);
            }
            if ($staff_id) {
                $ids = $staff_id;
            }
            if ($group_id || $staff_id) {
                $wheres['owner_staff_id'] = ['in', $ids];
            }
            $list = $this->model->where($where)
                ->where($wheres)->order($sort, $order)->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        $field = FormField::getFields(FormField::INSTOCK_TYPE);
        $this->assignconfig('fields', $field);
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {

                $params = $this->preExcludeFields($params);
                // 表单验证
                if (($result = $this->qingdongwmsValidate($params, 'Instock', 'create')) !== true) {
                    $this->error($result);
                }
                if(isset($params['flow_staff_ids'])){
                    if(!$params['flow_staff_ids']){
                        $this->error('请选择审批人');
                    }
                }
                if (isset($params['num'])) {
                    if (empty($params['num'])) {
                        $params['num'] = $this->model::getNum();
                    }
                    $instock = $this->model::where(['num' => $params['num']])->find();
                    if ($instock) {
                        $this->error('入库单编号已存在');
                    }
                } else {
                    $params['num'] = $this->model::getNum();
                }
                $result = FormField::checkFields(FormField::INSTOCK_TYPE, $params);
                if ($result !== true) {
                    $this->error($result);
                }
                Db::startTrans();
                try {
                    $params = Form::updateFormParams('instock', $params);
                    if ($params['product']) {
                        $params['product'] = json_decode($params['product'], true);
                    }
                    $result = $this->model::createInstock($params);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }


        $flow = Flow::getsteplist(Flow::INSTOCK_STATUS);
        if (empty($flow)) {
            $this->error('无可用审批流，请联系管理员','qingdongwms/work/flow');
        }
        //供应商
        $supplier = Supplier::where(['status'=>1])->order('sort desc')->select();
        //仓库
        $house = Warehouse::where(['status'=>1])->select();
        $this->assign('house', $house);
        $this->assign('supplier', $supplier);
        $this->assign('flow', $flow);
        $this->assign('staff', Staff::getStaff());
        $this->assign('customers', Customer::getList());
        $this->assign('customer_id', input('customer_id'));
        $this->assign('staffs', Staff::allList());
        $this->assign('form_data', Form::getDataValue('instock'));
        $this->assign('ratio', Ratio::where(['status' => 1])->select());
        return $this->view->fetch();
    }


    /**
     * 修改入库单
     * @param null $ids
     * @return string
     */
    public function edit($ids = null)
    {
        $map['id'] = $ids;
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            $params = $this->preExcludeFields($params);
            $row = $this->model::where(['id' => $ids, 'check_status' => ['in', [3, 4]]])->find();
            if (empty($row)) {
                $this->error('入库单审核中或已审核通过无法修改');
            }
            // 表单验证
            if (($result = $this->qingdongwmsValidate($params, 'Instock', 'create')) !== true) {
                $this->error($result);
            }
            $result = FormField::checkFields(FormField::INSTOCK_TYPE, $params,$ids);
            if ($result !== true) {
                $this->error($result);
            }

            Db::startTrans();
            try {
                $params = Form::updateFormParams('instock', $params);
                if ($params['product']) {
                    $params['product'] = json_decode($params['product'], true);
                }

                $params['id'] = $ids;
                $result = $this->model::updateInstock($params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('修改成功');
        }
        $row = $this->model->where($map)->find();
        $row = $row->toArray();
        $row = InstockOther::getOther($row);
        $flow = Flow::getsteplist(Flow::INSTOCK_STATUS);
        if (empty($flow)) {
            $this->error('无可用审批流，请联系管理员','qingdongwms/work/flow');
        }
        $product=InstockProduct::where(['instock_id'=>$ids])->select();
        foreach($product as $k=>$v){
            $product[$k]['product_name'] = Product::where(['id'=>$v['product_id']])->value('name');
        }
        $row['product']=json_encode($product,true);
        //供应商
        $supplier = Supplier::where(['status'=>1])->order('sort desc')->select();
        //仓库
        $house = Warehouse::where(['status'=>1])->select();
        $this->assign('house', $house);
        $this->assign('supplier', $supplier);
        $this->assign('flow', $flow);
        $this->view->assign("row", $row);
        $this->assign('customers', Customer::getList());
        $this->assign('staffs', Staff::getList());
        $this->assign('staff', Staff::getStaff());
        $this->assign('ratio', Ratio::where(['status' => 1])->select());
        $this->assign('form_data', Form::getDataValue('instock', $row));

        return $this->view->fetch();
    }


    /**
     * 入库单详情
     * @param null $ids
     * @return string
     */
    public function detail($ids = null)
    {
        $row = $this->model->where(['id' => $ids])->with([
            'ownerStaff'
        ])->find();
        if (empty($row)) {
            $this->error(__('No Results were found'));
        }
        $row = $row->toArray();
        $row = InstockOther::getOther($row);
        $row['warehouse'] = Warehouse::where(['id'=>$row['warehouse_id']])->value('name');
        $row['supplier'] = Supplier::where(['id'=>$row['supplier_id']])->value('name');
        $this->assign('examine_record', ExamineRecord::getList(ExamineRecord::INSTOCK_TYPE, $ids));

        $this->assign('flow', Flow::getstepdetail(Flow::INSTOCK_STATUS, $ids));
        //操作记录
        $log = OperationLog::getList(OperationLog::INSTOCK_TYPE, $ids);
        //标记通知已读
        Message::setRead(Message::INSTOCK_TYPE, $ids, $this->_staff->id);
        $this->assign('operation_log', $log);
        $this->assign('row', $row);
        $this->assign('ids', $ids);
        $this->assign('form_data', Form::getDataValue('instock', $row));
        $this->assignconfig("idinfo", ['id' => $ids]);
        return $this->view->fetch();
    }

    /**
     * 获取产品
     * @return \think\response\Json
     */
    public function get_product()
    {
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = $keyValue;
        }
        $name = input('name');
        if (!empty($name)) {
            $where['name'] = ['like', '%' . $name . '%'];
        }
        $countrys = Product::where($where)->field('id,name')->order('id desc')->select();
        return json(['list' => $countrys, 'total' => count($countrys)]);
    }

    /**
     * 获取产品配置
     * @return \think\response\Json
     */
    public function get_product_part()
    {
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = $keyValue;
        }
        $name = input('name');
        if (!empty($name)) {
            $where['name'] = ['like', '%' . $name . '%'];
        }
        $countrys = ProductPart::where($where)->field('id,name')->order('id desc')->select();
        return json(['list' => $countrys, 'total' => count($countrys)]);
    }

    /**
     * 获取产品价格
     */
    public function get_product_price()
    {
        $id = input('id', 0);
        $product = Product::where(['id' => $id])->with(['goods'])->find();
        if(empty($product)){
            $this->error('参数错误');
        }
        $this->success('请求成功', '',$product);
    }

    /**
     * 获取产品明细
     */
    public function get_instock_product(){
        $instock_id=input('instock_id',0,'intval');
        if(empty($instock_id)){
            $this->error('参数不能为空');
        }
        $products=InstockProduct::where(['instock_id'=>$instock_id])->with(['product'])->select();

        return json(['rows' =>$products, 'total' => count($products)]);
    }

    /**
     * 获取审批人列表
     */
    public function getstaff()
    {
        $pageSize = input('pageSize');
        $pageNumber = input('pageNumber');
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = ['in', $keyValue];
        }
        $name = input('name');
        if (!empty($name)) {
            $where['name'] = ['like', '%' . $name . '%'];
        }
        $staff = Staff::where($where)->where(['id' => ['neq', $this->_staff->id]])->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
        return json(['list' => $staff->items(), 'total' => $staff->total()]);
    }
    /**
     * 获取仓库
     */
    public function getwarehouse(){
        $pageSize = input('pageSize');
        $pageNumber = input('pageNumber');
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = ['in',$keyValue];
        }
        $name       = input('name');
        if(!empty($name)){
            $where['name'] = ['like','%'.$name.'%'];
        }
        $staff = Warehouse::where($where)->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
        return json(['list' => $staff->items(), 'total' => $staff->total()]);
    }
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $map['id'] = array('in', $ids);
        $result = $this->model->destroy($map);
        if (!$result) {
            $this->error('删除失败');
        }
        $this->success('删除成功');
    }
}
